<template>
	<view class="columnY container">
		<u-navbar :title="$t('loginPage.register')" placeholder bgColor="#12be98" leftIconColor="#FFFFFF"
			titleStyle="color: #FFFFFF" :rightText="$t('loginPage.choice')" @rightClick="hanldeChoice" autoBack>
		</u-navbar>
		<view class="centent">
			<view class="radius20 mar-top-40 pad-30 font-34">
				<!-- <Popover @change="switchFormMode" /> -->
				<up-form class="mar-top-30" labelPosition="left" :model="formData" :rules="rules" ref="ruleFrom">
					<!-- 昵称 -->
					<up-form-item prop="nickname" borderBottom="true">
						<up-input clearable placeholderClass="input-style" :placeholder="$t('register.username')"
							v-model="formData.nickname" border="none" />
					</up-form-item>
					<!-- 手机号 -->
					<up-form-item v-if="isMobile" prop="tel" class="mar-top-20" borderBottom="true">
						<view class="centerXY mar-right-26" @click="regionalPhoneVisibel = true">
							<text class="mar-right-6">{{columnsRegional[0]?.value || '+886'}}</text>
							<u-icon name="arrow-down-fill" color="#000000" size="14"></u-icon>
						</view>
						<up-input type="number" clearable placeholderClass="input-style"
							:placeholder="$t('loginPage.phoneTips')" v-model="formData.tel" border="none" />
					</up-form-item>
					<!-- 邮箱 -->
					<up-form-item v-else prop="nickname" class="mar-top-20" borderBottom="true">
						<up-input clearable placeholderClass="input-style" :placeholder="$t('email')" v-model="nickname"
							border="none" />
					</up-form-item>
					<!-- 验证码 -->
					<up-form-item prop="code" class="mar-top-20" borderBottom="true">
						<up-input type="number" clearable placeholderClass="input-style"
							:placeholder="$t('register.captcha_tips')" v-model="formData.code" border="none" />

						<up-button v-if="codeTime == 60" :text="$t('register.obtain_verification_code')" @click="hanldeCode" type="primary" :plain="true" color="#000000"
							:customStyle="{width: '300rpx'}"></up-button>
						<up-button v-else type="primary" :plain="true" color="#000000"
							:customStyle="{width: '300rpx'}">{{ codeText }}</up-button>
					</up-form-item>
					<!-- 密码 -->
					<up-form-item prop="login_secret" class="mar-top-20" borderBottom="true">
						<up-input clearable :type="showPassword ? 'text' :'password'" placeholderClass="input-style"
							:placeholder="$t('loginPage.passwordTips')" v-model="formData.login_secret" border="none">
							<template #suffix>
								<up-icon color="#888888" size="20" class="icon" @click="showPassword = !showPassword"
									:name="showPassword ? 'eye-fill' : 'eye-off'" />
							</template>
						</up-input>
					</up-form-item>
					<!-- 确认密码 -->
					<up-form-item prop="login_secret_confirmation" class="mar-top-20" borderBottom="true">
						<up-input clearable :type="againPasswordEye ? 'text' :'password'" placeholderClass="input-style"
							:placeholder="$t('register.again_password')" v-model="formData.login_secret_confirmation"
							border="none">
							<template #suffix>
								<u-icon color="#888888" size="20" class="icon"
									@click="againPasswordEye = !againPasswordEye"
									:name="againPasswordEye ? 'eye-fill' : 'eye-off'" />
							</template>
						</up-input>
					</up-form-item>
					<!-- 邀请码 -->
					<up-form-item prop="invite_code" class="mar-top-20" borderBottom="true">
						<u--input clearable placeholderClass="input-style"
							:placeholder="$t('register.please_invitation_code')" v-model="formData.invite_code"
							border="none" />
					</up-form-item>
				</up-form>
			</view>
		</view>
		<view class="pad-30 bg_color_fff">
			<view @click="hanldeLogin" class="mar-top-5 font-24 text-center">{{$t('register.account')}} <text
					class="color-main">{{$t('loginPage.title')}}</text></view>
			<u-button class="font-32 mar-top-10 bg-main" shape="circle" color="#edad14"
				@click="submit">{{$t('loginPage.register')}}</u-button>
		</view>
	</view>
	<regional-phone :show="regionalPhoneVisibel" @close="regionalPhoneVisibel = false" @confirm="handConfirm" />
</template>

<script setup>
	import Popover from '@/components/popover/popover.vue'
	import RegionalPhone from '@/components/regional-phone/index.vue'
	import {
		reactive,
		ref
	} from 'vue'
	import {
		useI18n
	} from 'vue-i18n'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		register,
		postCode
	} from '@/api/login.js'

	const {
		t
	} = useI18n()
	const formData = reactive({
		tel: '',
		login_secret: '',
		login_secret_confirmation: '',
		nickname: '',
		code: '',
		invite_code: uni.getStorageSync('code') || ''
	})
	const ruleFrom = ref(null)
	// 表单校验规则
	const rules = ref({
		nickname: [{
				required: true,
				message: t('register.nickname_cannot_empty'),
				trigger: 'blur'
			},
			// {
			// 	pattern: /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]+$/,
			// 	message: t('register.username'),
			// 	trigger: 'blur'
			// }
		],
		tel: [{
				required: true,
				message: t('loginPage.phoneTips'),
				trigger: 'blur'
			},
			// {
			// 	pattern: /^[0-9]*$/,
			// 	message: t('loginPage.correct_phone_number'),
			// 	trigger: 'blur'
			// }
		],
		code: [{
			required: true,
			message: t('register.captcha_tips'),
			trigger: 'blur'
		}],
		login_secret: [{
				required: true,
				message: t('loginPage.passwordTips'),
				trigger: 'blur'
			},
			{
				min: 6,
				message: t('my.should_least_digits'),
				trigger: 'blur'
			}
			// {
			// 	pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/,
			// 	message: t('message.password_contain_numbers_characters'),
			// 	trigger: 'blur'
			// }
		],
		login_secret_confirmation: [{
				required: true,
				message: t('register.again_password'),
				trigger: 'blur'
			},
			{
				validator: (rule, value, callback) => {
					if (value !== formData.login_secret) {
						callback(new Error(t('my.entered_inconsistent')));
					} else {
						callback();
					}
				},
				trigger: 'blur'
			}
		]
	})

	let codeTime = ref(60);
	let codeText = ref(`${t('register.obtainCode')}`);
	let inter = ref(null)

	// 获取验证码
	const hanldeCode = async () => {
		if (formData.tel == '') {
			uni.$u.toast(t('loginPage.phoneTips'))
			return
		}

		uni.showLoading({
			title: `${t('register.sending')}...`
		})

		const res = await postCode({
			tel: areaCode.value + formData.tel,
			scene: '6'
		});
		
		uni.hideLoading();
		clearInterval(inter.value);
		codeTime.value -= 1;
		codeText.value = `${codeTime.value}${t('register.again')}`;
		inter.value = setInterval(() => {
			codeTime.value -= 1
			codeText.value = `${codeTime.value}${t('register.again')}`;
			// 倒计时完成
			if (codeTime.value <= 0) {
				codeTime.value = `获取验证码`;
				codeTime.value = 60;
				clearInterval(inter.value);
			}
		}, 1000);

	}

	const regionalPhoneVisibel = ref(false)
	const showPassword = ref(false)
	const againPasswordEye = ref(false)
	const isMobile = ref(true) // 是否为手机号注册
	const columnsRegional = ref([])
	const areaCode = ref('+886');

	// 选择全球手机号
	const handConfirm = (event) => {
		columnsRegional.value = event;
		areaCode.value = event.value;
		regionalPhoneVisibel.value = false;
	}

	const validate = () => {
		return new Promise((resolve, reject) => {
			ruleFrom.value.validate().then(res => {
				resolve(true)
			}).catch(err => {
				uni.$u.toast(t('my.please_complete_information'))
				reject(err)
			})
		})
	}
	// 提交表单
	const submit = async () => {
		const result = await validate()
		const res = await register({
			...formData,
			tel: `${columnsRegional.value[0]?.value || '+886'}${formData.tel}`
		})
		if (res.code === 200) {
			uni.$u.toast(t('register.registered_successfully'))
			hanldeLogin()
		}
	}
	// 选择语言
	const hanldeChoice = () => {
		uni.navigateTo({
			url: '/pages/locale/locale'
		})
	}
	// 切换注册方式
	const switchFormMode = (event) => {
		switch (event) {
			case 0:
				isMobile.value = true
				break;
			case 1:
				isMobile.value = false
				break;
		}
	}
	// 跳转登录
	const hanldeLogin = () => {
		uni.redirectTo({
			url: '/pages/login/login'
		})
	}
</script>

<style lang="scss" scoped>
	:deep(.u-navbar__content__right__text) {
		color: #FFFFFF;
	}
	
	.container {
		height: 100vh;
		position: relative;

		.centent {
			flex-grow: 1;
			background: #FFFFFF;
		}
	}
</style>